package daos

import (
	"Bok/models"
	"fmt"

	"gorm.io/gorm"
)

type BlogDao interface {
	// 创建分类
	CreateBlogTypeDao(blogType *models.BlogTypeRequest) error
	// 修改分类
	EditBlogTypeDao(id uint, blogType *models.BlogTypeRequest) error
	// 查找分类
	GetBlogTypeList() ([]*models.BlogTypeResponse, error)
	// 删除分类
	DeleteBlogTypeDao(ids []uint) error
	// 根据名字查找
	FindBlogTypeByName(name string) (int64, error)
}

type blogDao struct {
	db *gorm.DB
}

func NewBlogDao(db *gorm.DB) BlogDao {
	return &blogDao{db: db}
}

func (c *blogDao) CreateBlogTypeDao(blogType *models.BlogTypeRequest) error {
	fmt.Println("dao:blogType:", blogType)
	err := c.db.Table("blog_types").Create(&blogType).Error
	if err != nil {
		fmt.Println("dao:blogType:111", err.Error())
		return err
	}
	return nil
}

func (c *blogDao) EditBlogTypeDao(id uint, blogType *models.BlogTypeRequest) error {
	err := c.db.Model(&models.BlogType{}).Where("id = ?", id).Updates(blogType).Error
	if err != nil {
		return err
	}
	return nil
}

func (c *blogDao) DeleteBlogTypeDao(ids []uint) error {
	for _, id := range ids {
		err := c.db.Delete(&models.BlogType{}, id).Error
		if err != nil {
			return err
		}
		return nil
	}
	return nil
}

func (c *blogDao) GetBlogTypeList() ([]*models.BlogTypeResponse, error) {
	var blogTypeList []*models.BlogTypeResponse
	err := c.db.Model(&models.BlogType{}).Find(&blogTypeList).Error
	if err != nil {
		return nil, err
	}
	return blogTypeList, nil
}

func (c *blogDao) FindBlogTypeByName(name string) (int64, error) {
	var count int64
	err := c.db.Model(&models.BlogType{}).Where("name = ?", name).Count(&count).Error
	if err != nil {
		return 0, err
	}
	return count, nil
}
